package pl.squeaky.mvc.generator;

import java.io.IOException;
import java.io.StringReader;

import org.eclipse.core.resources.IFile;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.php.internal.core.PHPCorePlugin;
import org.eclipse.php.internal.core.ast.nodes.ASTParser;
import org.eclipse.php.internal.core.ast.nodes.Program;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;

public class PhpGenerator extends Generator {
	protected Program program;
	
	public PhpGenerator() {
		ASTParser parser;
		try {
			parser = ASTParser.newParser(new StringReader(""), ASTParser.VERSION_PHP5);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		try {
			program = parser.createAST(null);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		program.recordModifications();
	}
	
	public void generate(IFile file) {
		IDocument document = new Document();
		TextEdit edit = program.rewrite(document, PHPCorePlugin.getOptions());
		try {
			edit.apply(document, TextEdit.UPDATE_REGIONS);
		} catch (MalformedTreeException e) {
			throw new RuntimeException(e);
		} catch (BadLocationException e) {
			throw new RuntimeException(e);
		}
		
		save(file, "<?php\n\n" + document.get());
	}
}
